<template>
  <div class="app-container">
    <!--  查询表单  -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="订单编号：" prop="orderId">
        <el-input v-model="queryParams.orderId" placeholder="请输入订单编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!--  订单列表  -->
    <div>
      <el-tabs v-model="tabsValue" type="border-card" @tab-click="tabsClick">
        <el-tab-pane v-for="(item,index) in tabsList" :key="index" :label="item.label" :name="item.name">
          <el-row style="margin-bottom: 10px">
            <!--          <el-button size="mini" type="primary" v-if="item.name == 103" @click="chooseOrder(chooseOrderList,701)">-->
            <!--            问题件驳回-->
            <!--          </el-button>-->
            <!--          <el-button size="mini" type="primary" v-if="item.name == 501" @click="chooseOrder(chooseOrderList,502)">-->
            <!--            同意截单-->
            <!--          </el-button>-->
            <!--          <el-button size="mini" type="danger" v-if="item.name == 501" @click="chooseOrder(chooseOrderList,503)">-->
            <!--            拒绝截单-->
            <!--          </el-button>-->
            <!--          <el-button size="mini" type="primary" v-if="item.name == 106" @click="chooseOrder(chooseOrderList,107)">-->
            <!--            同步国际运单号-->
            <!--          </el-button>-->
            <!--          <el-button size="mini" type="primary" v-if="item.name == 601" @click="chooseOrder(chooseOrderList,602)">-->
            <!--            同意仓储-->
            <!--          </el-button>-->
            <!--          <el-button size="mini" type="primary" v-if="item.name == 601" @click="chooseOrder(chooseOrderList,603)">-->
            <!--            拒绝仓储-->
            <!--          </el-button>-->
          </el-row>
          <el-table v-loading="loading" ref="multipleTable" :data="sellerOrderList" default-expand-all row-key="id"
                    :tree-props="{children: 'sellerChildOrderList'}" border @select-all="selectAllCheckbox"
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center">
              <template slot-scope="scope">
                <div v-if="!scope.row.childOrderId">
                  <el-checkbox v-model="scope.row.checkValue" @change="changeCheckbox(scope.row)"></el-checkbox>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="基本信息" min-width="250" prop="orderId">
              <template slot-scope="scope">
                <div v-if="!scope.row.childOrderId">
                  <div>
                    <span>买家姓名：</span>
                    <span>{{ scope.row.aeStoreOrderReceiptAddress.contactPerson }}</span>
                  </div>
                  <div>
                    <span>电话：</span>
                    <span>{{
                        scope.row.aeStoreOrderReceiptAddress.phoneCountry + scope.row.aeStoreOrderReceiptAddress.mobileNo
                      }}</span>
                  </div>
                  <div style="display: flex">
                    <span>国家：</span>
                    <span>
                    <dict-tag :options="dict.type.county_code"
                              :value="scope.row.aeStoreOrderReceiptAddress.country"></dict-tag>
                  </span>
                  </div>
                  <div>
                    <span>收货地址：</span>
                    <span>
                    {{ scope.row.aeStoreOrderReceiptAddress.detailAddress }}
                    {{ scope.row.aeStoreOrderReceiptAddress.city }}
                    {{ scope.row.aeStoreOrderReceiptAddress.province }}
                    {{ scope.row.aeStoreOrderReceiptAddress.country }}
                    {{ scope.row.aeStoreOrderReceiptAddress.zip }}
                  </span>
                  </div>
                  <!--                <div>-->
                  <!--                  <span>备注：</span>-->
                  <!--                  <span>{{ scope.row.memo }}</span>-->
                  <!--                </div>-->
                </div>
                <div v-else>
                  <div class="img-box">
                    <span>子订单号：</span>
                    <span>{{ scope.row.childOrderId }}</span>
                  </div>
                  <div class="img-box">
                    <span>商品主图：</span>
                    <imagePreview :src="scope.row.snapshotSmallPhotoPath" width="50px" height="50px"/>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品信息" min-width="300">
              <template slot-scope="scope">
                <div v-if="scope.row.childOrderId">
                  <div>
                    <span>ProductID：</span>
                    <span>{{ scope.row.productId }}</span>
                  </div>
                  <div>
                    <span>产品ID：</span>
                    <span>{{ scope.row.collectProductId }}</span>
                  </div>
                  <div>
                    <span>商品编码：</span>
                    <span>{{ scope.row.skuCode }}</span>
                  </div>
                  <div>
                    <el-tooltip effect="dark" :content="scope.row.productName" placement="top">
                      <el-button type="text">
                        <div class="hidden-box">
                          <span>商品名称：</span>
                          <span>{{ scope.row.productName }}</span>
                        </div>
                      </el-button>
                    </el-tooltip>
                  </div>
                  <div>
                    <span>买家选择物流方式：</span>
                    <span>{{ scope.row.logisticsType }}</span>
                  </div>
                  <!--                  <div>-->
                  <!--                    <span>尺寸(长宽高重量)：</span>-->
                  <!--                    <span>{{ scope.row.sku.skuLength }}*</span>-->
                  <!--                    <span>{{ scope.row.sku.skuWidth }}*</span>-->
                  <!--                    <span>{{ scope.row.sku.skuHeight }}*</span>-->
                  <!--                    <span>{{ scope.row.sku.skuWeight }}</span>-->
                  <!--                  </div>-->
                </div>
                <div v-else>
                  <div v-if="scope.row.leftEndGoodTime" style="color: #ff4949">
                    <span>剩余时间：</span>
                    <span>
                    <count-down :endTime="endTime(scope.row.leftEndGoodTime)" endText="已结束"/>
                  </span>
                  </div>
                  <div style="display: flex">
                    <span>物流状态：</span>
                    <span>
                    <dict-tag :options="dict.type.erp_logistics_type" :value="scope.row.logisticsType"></dict-tag>
                  </span>
                  </div>
                  订单号：{{ scope.row.orderId }}
                  <div>
                    <span>店铺：</span>
                    <span>{{ scope.row.sellerLoginId }}</span>
                  </div>
                  <div>
                    <span>卖家全名：</span>
                    <span>{{ scope.row.sellerSignerFullname }}</span>
                  </div>
                  <div>
                    <span>所属公司：</span>
                    <span>
                     <el-button size="mini" type="text"
                                @click="getErpAgentBranchInfo(scope.row)">查看所属公司</el-button>
                  </span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="订单金额" prop="bizType" min-width="180">
              <template slot-scope="scope">
                <div v-if="scope.row.childOrderId">
                  <div>
                    <span>采购成本：</span>
                    <span v-if="scope.row.orderData.payCurrencyCode == 'USD'">
                    {{ scope.row.skuPrice == null ? '未知' : countPrice(scope.row.skuPrice) + 'RMB' }}
                  </span>
                    <span v-else>{{
                        scope.row.skuPrice == null ? '未知' : countPrice(scope.row.skuPrice) + 'RMB'
                      }} </span>
                  </div>
                  <div>
                    <span>商品数量：</span>
                    <span>{{ scope.row.productCount }}</span>
                  </div>
                  <div>
                    <span>商品规格：</span>
                    <span>{{ scope.row.skuPropertyIds }}</span>
                  </div>
                </div>
                <div v-else>
                  <div v-if="scope.row.payCurrencyCode == 'USD'">
                    <div>订单金额：{{ countPrice(scope.row.payAmount) }} RMB</div>
                    <div>联盟佣金：{{ countPrice(scope.row.afflicateFeeRate) }} RMB</div>
                    <div>交易佣金：{{ countPrice(scope.row.escrowFeeRate) }} RMB</div>
                    <div>预估利润：
                      {{
                        scope.row.estimatedProfit == null ? '未知' : scope.row.estimatedProfit + 'RMB'
                      }}
                    </div>
                  </div>
                  <div v-else>
                    <div>订单金额：{{ countPrice(scope.row.payAmount) }} RMB</div>
                    <div>联盟佣金：{{ countPrice(scope.row.afflicateFeeRate) }} RMB</div>
                    <div>交易佣金：{{ countPrice(scope.row.escrowFeeRate) }} RMB</div>
                    <div>预估利润：{{
                        scope.row.estimatedProfit == null ? '未知' : scope.row.estimatedProfit + 'RMB'
                      }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="时间" prop="orderStatus" min-width="200">
              <template slot-scope="scope">
                <div v-if="scope.row.childOrderId">
                  <div>创建时间：{{ scope.row.orderData.gmtCreate }}</div>
                  <div>付款时间： {{ scope.row.orderData.gmtPayTime }}</div>
                  <div>更新时间： {{ scope.row.orderData.updateTime }}</div>
                  <div v-if="scope.row.erpInnerOrderStatus != '103' && scope.row.erpInnerOrderStatus != '1031'">
                    <span>国内运单号：</span>
                    <span>{{ scope.row.trackingNo }}</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center" fixed="right">
              <template slot-scope="scope">
                <div v-if="scope.row.childOrderId">
                  <el-button size="mini" type="text" @click="openShippingModal(scope.row)">声明发货</el-button>
<!--                  <el-button size="mini" type="text" @click="transferStorage(scope.row)">转仓储</el-button>-->
                </div>
                <div v-else>
                  <el-button size="mini" type="text" @click="openOrderDetail(scope.row)">详情</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </div>
    <!--  订单详情  -->
    <order-detail v-if="isOpenOrderDetail" :id="orderId" @orderDetailSwitch="orderDetailSwitch"></order-detail>

    <!--  填写声明发货信息  -->
    <el-dialog title="声明发货信息" :visible.sync="isEditShippingInfo" width="500px">
      <el-form :model="shippingInfo" ref="shippingInfo" size="small" :rules="shippingInfoRules"
               label-width="120px">
        <el-form-item label="国际运单号：" prop="intlTrackingNo">
          <el-input v-model="shippingInfo.intlTrackingNo" placeholder="请输入国际运单号" clearable/>
        </el-form-item>
        <el-form-item label="运费：" prop="realityLogisticsPrice">
          <el-input v-model="shippingInfo.realityLogisticsPrice" placeholder="请输入运费" clearable/>
        </el-form-item>
        <el-form-item label="其它费用：" prop="otherLogisticsPrice">
          <el-input v-model="shippingInfo.otherLogisticsPrice" placeholder="请输入其它运费" clearable/>
        </el-form-item>
        <el-form-item label="运费凭证：" prop="logisticsProof">
          <image-upload v-model="shippingInfo.logisticsProof" :is-show-tip="false" width="50px" height="50px"/>
        </el-form-item>
        <!--        <el-form-item label="实际承运商：" prop="actualCarrier">-->
        <!--          <el-input v-model="shippingInfo.actualCarrier" placeholder="请输入实际承运商" clearable/>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" style="display: flex;justify-content: space-between">
        <div>
          <el-button size="small" type="success" @click="declarationShipment('1')">声明发货</el-button>
          <el-button size="small" type="danger" @click="declarationShipment('2')">转线下发货</el-button>
        </div>
        <div>
          <el-button size="small" @click="isEditShippingInfo = false">取 消</el-button>
          <el-button size="small" type="primary" @click="declarationShipment('0')">保存信息</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 转仓储选择仓库 -->
    <el-dialog
      title="转仓储选择仓库"
      :visible.sync="isTransfer"
      width="670px">
      <div class="edit-box">
        <el-form size="small" :model="transferForm" :rules="transferRules" ref="transferRef"
                 label-width="120px">
          <el-form-item label="选择仓库：" prop="warehouseId">
            <el-select v-model="transferForm.warehouseId" placeholder="请选择仓库" size="small">
              <el-option
                v-for="dict in warehouseList"
                :key="dict.warehouseName"
                :label="dict.warehouseName"
                :value="dict.warehouseId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isTransfer = false">取 消</el-button>
        <el-button type="primary" @click="confirmTransfer()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import orderDetail from '@/views/components/order/order-detail.vue'
import countDown from '@/views/components/countDown/index.vue';
import {
  getErpAgentBranchInfo,
  listSellerOrder
} from '@/api/order/purchaser'
import {saveShipmentInfoForOther, sellerShipmentForOther} from "@/api/order/packGroup";
import {
  addWarehousInfo,
  warehouseList
} from "@/api/warehouse/warehouse";
import {queryOrderSendGoodsInfo} from "@/api/order/orderApi";

export default {
  name: 'SellerOrder',
  components: {
    orderDetail,
    countDown,
  },
  dicts: ['county_code', 'erp_logistics_type'],
  data() {
    return {
      checkValue: false,
      orderId: '',
      loading: false, // 遮罩层
      chooseOrderList: [], // 选中数组
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      showSearch: true, // 显示搜索条件
      total: 0, // 总条数
      sellerOrderList: [], // 卖家订单表格数据
      title: '订单详情', // 弹出层标题
      isOpenOrderDetail: false, // 是否打开订单详情弹窗
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: undefined,
        // erpInnerOrderStatus: "108",
        statusList: "108",
        orderProcessFlag: 'offline',
        type: '1',
      }, // 查询参数
      tabsValue: '108',
      tabsList: [{
        name: '108',
        label: '待声明发货'
      }],
      isChooseOrder: false,//是否选择订单
      isEditShippingInfo: false,//是否打开填写声明发货信息弹窗
      shippingInfoRules: {
        intlTrackingNo: [{required: true, message: '国际运单号不能为空', trigger: 'blur'}],
        realityLogisticsPrice: [{required: true, message: '运费不能为空', trigger: 'blur'}],
        otherLogisticsPrice: [{required: true, message: '其它运费不能为空', trigger: 'blur'}],
        actualCarrier: [{required: false, message: '实际承运商不能为空', trigger: 'blur'}],
        logisticsProof: [{required: true, message: '请上传运费凭证', trigger: 'change'}],
      },
      shippingInfo: {},
      isTransfer: false,
      transferForm: {},
      transferRules: {
        warehouseId: [{required: true, message: '请选择仓库', trigger: 'change'}]
      },
      warehouseList: [] // 仓库列表
    }
  },
  computed: {
    endTime() {
      return time => {
        return new Date(time).getTime() / 1000 + ' '
      }
    }
  },
  created() {
    this.userInfo = this.$store.state.user.urserInfo;
    this.getList();
    // this.getWarehouseList();
  },
  methods: {
    // 获取订单店铺层级关系
    getErpAgentBranchInfo(row) {
      getErpAgentBranchInfo({sellerLoginId: row.sellerLoginId}).then(res => {
        let list = res.data;
        let message = "";
        for (let i = 0; i < list.length; i++) {
          message += `<div>` + list[i].branch + '——' + list[i].agent + '——' + list[i].userInfo + `</div>`
        }
        // console.log('***', message)
        this.$confirm(message, '所属公司', {
          dangerouslyUseHTMLString: true,
        }).then(() => {

        })
      })
    },
    // 获取仓库列表
    getWarehouseList() {
      warehouseList().then(response => {
        this.warehouseList = response.data;
      });
    },
    // 转仓储
    transferStorage(row) {
      this.isTransfer = true;
      this.transferForm.childOrderId = row.id;
      this.transferForm.type = '0';
    },
    // 转仓储
    confirmTransfer() {
      this.$refs["transferRef"].validate(valid => {
        if (valid) {
          addWarehousInfo(this.transferForm).then(response => {
            this.$message({
              type: 'success',
              message: response.msg
            })
            this.isTransfer = false;
            this.getList();
          }).finally(() => {
            this.isTransfer = false;
          })
        }
      })
    },
    // 切换选项卡
    tabsClick(tab, event) {
      this.queryParams.statusList = tab.name
      this.getList()
    },
    // 订单详情弹窗开关
    orderDetailSwitch(e) {
      this.isOpenOrderDetail = e
    },
    /** 查询卖家订单列表 */
    getList() {
      this.loading = true
      listSellerOrder(this.queryParams).then(response => {
        let list = response.rows
        this.sellerOrderList = list
        for (let i = 0; i < list.length; i++) {
          this.sellerOrderList[i]['checkValue'] = false
          for (let j = 0; j < list[i].sellerChildOrderList.length; j++) {
            if (list[i].orderId == list[i].sellerChildOrderList[j].orderId) {
              this.sellerOrderList[i].sellerChildOrderList[j]['erpInnerOrderStatus'] = this.sellerOrderList[i].erpInnerOrderStatus
              this.sellerOrderList[i].sellerChildOrderList[j]['orderData'] = this.sellerOrderList[i]
              this.sellerOrderList[i].sellerChildOrderList[j].id = String(this.sellerOrderList[i].sellerChildOrderList[j].id)
            }
          }
        }
        // console.log('this.sellerOrderList', this.sellerOrderList)
        this.chooseOrderList = [] // 清空所选择的订单
        this.total = response.total
        this.loading = false
      })
    },
    // 打开填写声明发货信息弹窗
    openShippingModal(row) {
      this.shippingInfo = {}
      this.shippingInfo.childIds = row.childOrderId
      this.isEditShippingInfo = true
      this.orderId = row.orderId
      queryOrderSendGoodsInfo({orderId: row.orderId}).then(res => {
        this.shippingInfo = res.data
      })
    },
    // 声明发货
    declarationShipment(e) {
      this.$refs['shippingInfo'].validate(valid => {
        if (valid) {
          if (e == '0') { //保存信息
            console.log('this.shippingInfo', this.shippingInfo)
            this.$confirm("是否确定提交声明发货信息？", '提示').then(() => {
              this.shippingInfo.type = e
              saveShipmentInfoForOther(this.shippingInfo).then(res => {
                this.$message.success(res.msg)
                this.isEditShippingInfo = false
                this.getList()
              })
            })
          } else {//声明发货
            sellerShipmentForOther({
              orderId: this.orderId,
              type: e
            }).then(res => {
              this.$message.success(res.msg)
              this.isEditShippingInfo = false
              this.getList()
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.isOpenOrderDetail = false
      this.reset()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(val) {
      // this.multipleSelection = val;
    },
    // 全选
    selectAllCheckbox(selection) {
      this.chooseOrderList = []
      if (selection.length > 0) {
        this.checkValue = true
        selection.forEach((item, index) => {
          this.sellerOrderList[index].checkValue = true
          this.chooseOrderList.push(item.orderId)
        })
      } else {
        this.sellerOrderList.forEach((item, index) => {
          this.sellerOrderList[index].checkValue = false
        })
      }
    },
    // 选择单选框
    changeCheckbox(selection) {
      for (let i = 0; i < this.sellerOrderList.length; i++) {
        if (this.sellerOrderList[i].orderId == selection.orderId) {
          this.chooseOrderList.push(selection.orderId)
        }
      }
      this.isChooseOrder = !this.isChooseOrder
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //查看订单详情
    openOrderDetail(row) {
      this.orderId = row.orderId
      this.isOpenOrderDetail = true
    },
    jumpPage(skuBuyLink) {
      window.open(skuBuyLink)
    }
  }
}
</script>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}


.demo-table-expand label {
  width: 100px;
  color: #99a9bf;
  padding: 0;
}

.el-form-item el-form-item--small {
  margin-bottom: 0;
}

.el-form--label-left .el-form-item__label {
  text-align: right;
}

.demo-table-expand .el-form-item {
  width: 16%;
  margin-bottom: 0;
  margin-right: 0;
}

.img-box {
  display: flex;
  align-items: flex-start;
}

.edit-box {
  display: flex;
  align-items: center;
  /*justify-content: space-between;*/
  margin-bottom: 20px;
}

.edit-box-name {
  width: 120px;
  text-align: right;
}

.edit-box input {
  display: block;
}

/*去掉number输入框的上下箭头*/
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

input[type="number"] {
  -moz-appearance: textfield;
}

/*解决输入中文后光标上移的问题*/
.el-input__inner {
  line-height: 1px !important;
}
</style>
